<script setup>
import { FileUploadPublic } from '@/api';
import { ref, reactive, onMounted } from 'vue';

const popup = ref(null);
const RefRecorde = ref(null);
const emit = defineEmits(['recordBack']);

const info = reactive({
  iconColor: '#000',
  voicePath: '',
  recordFlag: true,
  baseTime: 30, // 基础时长30秒
  recordTime: 30,
});
let countdownInterval = null;
let shouldUpload = true; // 是否上传服务器

// 使用条件编译初始化录音管理器
let recorderManager;
// #ifdef APP-PLUS
recorderManager = plus.audio.getRecorder();
// #endif
// #ifdef H5
recorderManager = uni.getRecorderManager();
// #endif

const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;

const open = () => popup.value.open();
const close = () => popup.value.close();

const startRecord = () => {
  console.log('开始录音');
  info.iconColor = '#f00';
  info.recordFlag = false;
  shouldUpload = true;

  info.recordTime = 30;
  countdownInterval = setInterval(() => {
    if (info.recordTime > 0) {
      info.recordTime--;
    } else {
      endRecord(); // 如果倒计时结束，自动停止录音
    }
  }, 1000);

  // #ifdef APP-PLUS
  recorderManager.record(
    { filename: '_doc/audio/' },
    function () {
      console.log('Audio record success!');
    },
    function (e) {
      console.log('Audio record failed: ' + e.message);
    }
  );
  // #endif
  // #ifdef H5
  recorderManager.start({
    duration: 30 * 1000, // 录音的最大时长，单位 ms，这里设置为30秒
    sampleRate: 16000, // 采样率
  });
  // #endif
};

const endRecord = () => {
  console.log('停止录音');

  info.iconColor = '#000';
  info.recordFlag = true;

  // #ifdef APP-PLUS
  recorderManager.stop();
  // #endif
  // #ifdef H5
  recorderManager.stop();
  // #endif

  clearInterval(countdownInterval);
  info.recordTime = info.baseTime; // 重置倒计时
  close();
};

const closeAndStopRecord = () => {
  shouldUpload = false; // 点击空白处不上传
  endRecord(); // 停止录音
};

onMounted(() => {
  // #ifdef H5
  recorderManager.onStop(function (res) {
    console.log('是否上传');
    if (!shouldUpload) {
      console.log('不要上传');
      return;
    }
    console.log('去上传');
    console.log('recorder stop' + JSON.stringify(res));
    info.voicePath = res.tempFilePath;

    FileUploadPublic({
      filePath: res.tempFilePath,
    })
      .then((res) => {
        console.log(res);
        if (res.statusCode === 200) {
          const backData = JSON.parse(res.data);
          if (backData.code === '0') {
            emit('recordBack', backData.data);
          } else {
            uni.showToast({
              title: '录音上传失败',
              icon: 'none',
            });
          }
        } else {
          uni.showToast({
            title: '录音上传失败',
            icon: 'none',
          });
        }
      })
      .catch((err) => {
        console.log('录音 err', err);
        uni.showToast({
          title: '录音上传失败',
          icon: 'none',
        });
      });
  });
  // #endif
});

defineExpose({
  open,
  close,
});
</script>
